package wnhz.com.business.groupshop.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import wnhz.com.business.R;
import wnhz.com.business.groupshop.adapter.MyPublicTaskRecycleAdapter;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyBitmapUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.Confirg;
import wnhz.com.business.view.ShowImageDetail;
import wnhz.com.business.view.TranslucentActionBar;

public class EvaluateActivity extends BaseActivity implements ActionBarClickListener, View.OnClickListener, View.OnLongClickListener {

    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;
    @BindView(R.id.jion_recyclerView)
    RecyclerView jion_recyclerView;
    @BindView(R.id.tv_good)
    TextView tv_good;
    @BindView(R.id.tv_middle)
    TextView tv_middle;
    @BindView(R.id.tv_bad)
    TextView tv_bad;
    @BindView(R.id.tv_youtu)
    TextView tv_youtu;

    @BindView(R.id.et_content)
    EditText et_content;

    private ArrayList<String> imagePaths = new ArrayList<>();
    private String compressImageFilePath;
    private MyPublicTaskRecycleAdapter mTaskImgAdapter;
    private List<Integer> imageRes = new ArrayList<>();
    private final int FROM_ALBUM_CODE = 102;// 调用相册更改背景图片的请求code
    private ArrayList<String> compressPaths = new ArrayList<>();
    private List<TextView> textViews = new ArrayList<>();
    private int size;
    private String orderId;
    private int pl = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate);
        ButterKnife.bind(this);
        orderId = getIntent().getStringExtra("orderId");
        actionbar.setData("商品评价", R.drawable.ic_lefft_white, null, 0, "发布", 0,this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }
        initData();
        initView();
    }

    private void initData() {
        imagePaths.add(R.mipmap.bg_fabu_img542x + "");
        compressImageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/WorksComing/Compress/";
        File folder = new File(compressImageFilePath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    private void initView() {
        textViews.add(tv_good);
        textViews.add(tv_middle);
        textViews.add(tv_bad);
        textViews.add(tv_youtu);

        tv_good.setOnClickListener(this);
        tv_middle.setOnClickListener(this);
        tv_bad.setOnClickListener(this);
        tv_youtu.setOnClickListener(this);
        jion_recyclerView.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
        mTaskImgAdapter = new MyPublicTaskRecycleAdapter(EvaluateActivity.this, imageRes, imagePaths, EvaluateActivity.this, EvaluateActivity.this);
        jion_recyclerView.setAdapter(mTaskImgAdapter);
    }

    @Override
    public void onLeftClick() {
        finish();

    }

    @Override
    public void onRightClick() {
        if (pl == 4) {
            MyToast("请选择评价类型");
            return;
        } else {
//            UpFaNuTextData();
        }
    }

    @Override
    public void onEditTextClick() {

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.tv_good:
                pl = 1;
                changeColor(0);
                break;
            case R.id.tv_middle:
                pl = 2;
                changeColor(1);
                break;
            case R.id.tv_bad:
                pl = 3;
                changeColor(2);
                break;
            case R.id.tv_youtu:
                pl = 4;
                changeColor(3);
                break;
            case R.id.item_publishTask_image:
                Integer index = (Integer) v.getTag();
                if (index == imagePaths.size() - 1) {

                    if (imagePaths.size() >= 7) {
                        Toast.makeText(EvaluateActivity.this, "最多选择6张图片", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    intent = new Intent(EvaluateActivity.this, MultiImageSelectorActivity.class);
                    // 是否显示调用相机拍照
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                    // 最大图片选择数量
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 7 - imagePaths.size());
                    // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);

                    startActivityForResult(intent, FROM_ALBUM_CODE);
                } else {
                    ArrayList<String> paths = new ArrayList<>();
                    paths.addAll(imagePaths);
                    paths.remove(paths.get(paths.size() - 1));

                    intent = new Intent(EvaluateActivity.this, ShowImageDetail.class);
                    intent.putStringArrayListExtra("paths", paths);
                    intent.putExtra("index", index);
                    startActivity(intent);
                }
                break;
        }
    }

    public void changeColor(int position) {
        for (int i = 0; i < textViews.size(); i++) {
            if (i == position) {
                textViews.get(i).setTextColor(getResources().getColor(R.color.white));
                textViews.get(i).setBackgroundResource(R.drawable.bg_circle_green);
            } else {
                textViews.get(i).setTextColor(getResources().getColor(R.color.text_black1));
                textViews.get(i).setBackgroundResource(R.drawable.bg_circle_comment);
            }
        }
    }

    @Override
    public boolean onLongClick(View v) {
        final Integer index = (Integer) v.getTag();
        /**
         这里使用了 android.support.v7.app.AlertDialog.Builder
         可以直接在头部写 import android.support.v7.app.AlertDialog
         那么下面就可以写成 AlertDialog.Builder
         */
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setMessage("是否确认删除？");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                imagePaths.remove(imagePaths.get(index));
                compressPaths.remove(compressPaths.get(index));
                mTaskImgAdapter.notifyDataSetChanged();
            }
        });
        if (imagePaths.size() - 1 != index)
            builder.show();

        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {

                //相册
                case FROM_ALBUM_CODE:
                    if (null != data) {
                        if (!Confirg.compressFile.exists()) {
                            Confirg.compressFile = new File(Confirg.FilesPath);
                            Confirg.compressFile.mkdirs();
                        }

                        List<String> list = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                        System.out.println("========：" + list.size());
                        if (imagePaths.size() < 7) {
                            for (int i = 0; i < list.size(); i++) {
                                System.out.println("选中的路径：" + list.get(i));

                                String pic_path = list.get(i);
                                String targetPath = compressImageFilePath + Confirg.df.format(new Date()) + ".jpg";
                                //调用压缩图片的方法，返回压缩后的图片path
                                final String compressImage = MyBitmapUtils.compressImage(pic_path, targetPath, 40);
                                LogUtils.e("==f3imgcc==", "onActivityResult: ===compressImage==压缩图片路径==" + compressImage);
                                compressPaths.add(compressImage);
                                imagePaths.add(imagePaths.size() - 1, list.get(i));
                            }
                        } else {
                            Toast.makeText(EvaluateActivity.this, "无法添加更多图片！", Toast.LENGTH_SHORT).show();
                        }
                        mTaskImgAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    private void UpFaNuTextData() {
        if (et_content.getText().toString().equals("")) {
            MyToast("请输入发布内容");
            return;
        }

        size = compressPaths.size();
        if (size == 0) {
            MyToast("请添加图片");
            return;
        }

        showDialog("");
        Map<String, Object> map = new HashMap<>();
//        if (MyApplication.getInstance().userBean != null) {
//            map.put("token", MyApplication.getInstance().userBean.getToken());
//        }

        List<File> files = new ArrayList<>();

        if (size > 0) {
            for (int i = 0; i < size; i++) {
                map.put("imgs" + ( i + 1), new File(compressPaths.get(i)));
            }
        }

        map.put("content", et_content.getText().toString());
        map.put("type", pl);
        map.put("orderId", orderId);
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("--发布参数--==" + key, "" + value + "\n");
            }
        }
        XUtil.Post(Url.Order_evaluateOrder, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    Log.e("===发布=", jsonObject.toString());
                    if ("1".equals(jsonObject.optString("re"))) {
                        Intent intent = new Intent();
                        intent.putExtra("refresh", "1");
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                    MyToast(jsonObject.optString("info"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });


    }
}
